<template>
  <div class="tab-content-container user-posts">
    <h3 class="section-title">我的发布</h3>

    <div class="content-scroll-area">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="寻物启事" name="lost">
          <div class="tab-header">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索我的寻物启事"
              :prefix-icon="SearchIcon"
              clearable
              @clear="loadLostItems"
              @input="debounceSearch"
            />
            <el-button
              class="xunwu"
              type="primary"
              @click="$router.push('/publish?type=lost')"
            >
              <el-icon><Plus /></el-icon>发布寻物启事
            </el-button>
          </div>

          <el-table :data="lostItems" style="width: 100%" v-loading="loading">
            <el-table-column prop="name" label="物品名称" width="150" />
            <el-table-column prop="time" label="发布时间" width="150">
              <template #default="scope">
                {{ formatDate(scope.row.time) }}
              </template>
            </el-table-column>
            <el-table-column prop="location" label="丢失地点" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <div class="action-buttons">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button
                      type="primary"
                      circle
                      size="small"
                      @click="viewDetails(scope.row)"
                    >
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>

                  <el-tooltip content="编辑信息" placement="top">
                    <el-button
                      type="warning"
                      circle
                      size="small"
                      @click="editItem(scope.row)"
                    >
                      <el-icon><Edit /></el-icon>
                    </el-button>
                  </el-tooltip>

                  <el-tooltip content="删除" placement="top">
                    <el-button
                      type="danger"
                      circle
                      size="small"
                      @click="deleteItem(scope.row)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <el-empty
            v-if="lostItems.length === 0 && !loading"
            description="暂无寻物启事"
          >
            <el-button
              type="primary"
              @click="$router.push('/publish?type=lost')"
            >
              立即发布
            </el-button>
          </el-empty>

          <div class="pagination-container" v-if="lostItems.length > 0">
            <el-pagination
              layout="prev, pager, next"
              :total="lostTotal"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="失物招领" name="found">
          <div class="tab-header">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索我的失物招领"
              :prefix-icon="SearchIcon"
              clearable
              @clear="loadFoundItems"
              @input="debounceSearch"
            />
            <el-button
              :style="{ marginRight: '38px' }"
              type="primary"
              @click="$router.push('/publish?type=found')"
            >
              <el-icon><Plus /></el-icon>发布失物招领
            </el-button>
          </div>

          <el-table :data="foundItems" style="width: 100%" v-loading="loading">
            <el-table-column prop="name" label="物品名称" width="150" />
            <el-table-column prop="time" label="发布时间" width="150">
              <template #default="scope">
                {{ formatDate(scope.row.time) }}
              </template>
            </el-table-column>
            <el-table-column prop="location" label="拾获地点" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <div class="action-buttons">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button
                      type="primary"
                      circle
                      size="small"
                      @click="viewDetails(scope.row)"
                    >
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>

                  <el-tooltip content="编辑信息" placement="top">
                    <el-button
                      type="warning"
                      circle
                      size="small"
                      @click="editItem(scope.row)"
                    >
                      <el-icon><Edit /></el-icon>
                    </el-button>
                  </el-tooltip>

                  <el-tooltip content="删除" placement="top">
                    <el-button
                      type="danger"
                      circle
                      size="small"
                      @click="deleteItem(scope.row)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <el-empty
            v-if="foundItems.length === 0 && !loading"
            description="暂无失物招领"
          >
            <el-button
              type="primary"
              @click="$router.push('/publish?type=found')"
            >
              立即发布
            </el-button>
          </el-empty>

          <div class="pagination-container" v-if="foundItems.length > 0">
            <el-pagination
              layout="prev, pager, next"
              :total="foundTotal"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%">
      <span>确定要删除这条信息吗？删除后将无法恢复。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, watch } from "vue";
import {
  Plus,
  View,
  Edit,
  Delete,
  Search as SearchIcon, // 重命名为 SearchIcon 以区分图标和组件
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus"; // 移除未使用的 ElMessageBox
import api from "@/utils/api";
import { useRouter } from "vue-router";

export default {
  name: "UserPosts",
  props: {
    userId: {
      type: String,
      required: true,
    },
  },
  components: {
    Plus,
    View,
    Edit,
    Delete,
    // 移除未使用的 Search 组件注册
  },
  setup() {
    const activeTab = ref("lost");
    const loading = ref(false);
    const searchKeyword = ref("");
    const currentPage = ref(1);
    const pageSize = ref(10);
    const lostTotal = ref(0);
    const foundTotal = ref(0);
    const lostItems = ref([]);
    const foundItems = ref([]);
    const deleteDialogVisible = ref(false);
    const itemToDelete = ref(null);
    const router = useRouter();

    // 监听标签页变化，切换时重置分页并加载数据
    const handleTabChange = () => {
      // 添加一点延迟，让视图有时间渲染
      setTimeout(() => {
        if (activeTab.value === "lost") {
          loadLostItems();
        } else {
          loadFoundItems();
        }
      }, 50);
    };

    // 监听标签页变化
    watch(activeTab, handleTabChange);

    // 加载寻物启事列表
    const loadLostItems = async () => {
      loading.value = true;
      try {
        const response = await api.get("/user/posts/lost", {
          params: {
            page: currentPage.value,
            size: pageSize.value,
            keyword: searchKeyword.value,
          },
        });

        if (response.data.code === 200) {
          lostItems.value = response.data.data.items;
          lostTotal.value = response.data.data.total;
        } else {
          ElMessage.warning(response.data.message || "获取寻物启事失败");
        }
      } catch (error) {
        console.error("获取寻物启事失败:", error);
        ElMessage.error("获取寻物启事失败，请稍后再试");
      } finally {
        loading.value = false;
      }
    };

    // 加载失物招领列表
    const loadFoundItems = async () => {
      loading.value = true;
      try {
        const response = await api.get("/user/posts/found", {
          params: {
            page: currentPage.value,
            size: pageSize.value,
            keyword: searchKeyword.value,
          },
        });

        if (response.data.code === 200) {
          foundItems.value = response.data.data.items;
          foundTotal.value = response.data.data.total;
        } else {
          ElMessage.warning(response.data.message || "获取失物招领失败");
        }
      } catch (error) {
        console.error("获取失物招领失败:", error);
        ElMessage.error("获取失物招领失败，请稍后再试");
      } finally {
        loading.value = false;
      }
    };

    // 根据状态获取标签类型
    const getStatusType = (status) => {
      const typeMap = {
        待认领: "warning",
        认领中: "info",
        已认领: "success",
        已关闭: "danger",
        已过期: "info",
      };
      return typeMap[status] || "default";
    };

    // 查看详情
    const viewDetails = (item) => {
      // 确保我们有有效的ID
      if (!item || !item.id) {
        ElMessage.warning("无法查看：物品ID不存在");
        return;
      }

      // 获取当前选中的标签页类型
      const routeType = activeTab.value; // "lost" 或 "found"

      // 打印调试信息
      console.log(`准备跳转到: /${routeType}/${item.id}`);

      try {
        // 使用路由导航而不是window.open
        router.push(`/${routeType}/${item.id}`);
      } catch (error) {
        console.error("导航失败:", error);
        // 后备方案：如果路由导航失败，使用window.open
        window.open(`/${routeType}/${item.id}`, "_blank");
      }
    };

    // 编辑物品
    const editItem = (item) => {
      // 跳转到编辑页面
      const type = activeTab.value;
      window.open(`/publish?id=${item.id}&type=${type}`, "_blank");
    };

    // 删除物品
    const deleteItem = (item) => {
      itemToDelete.value = item;
      deleteDialogVisible.value = true;
    };

    // 确认删除
    const confirmDelete = async () => {
      if (!itemToDelete.value) return;

      try {
        const type = activeTab.value;
        const response = await api.delete(
          `/user/posts/${type}/${itemToDelete.value.id}`
        );

        if (response.data.code === 200) {
          ElMessage.success("删除成功");

          // 从列表中移除
          if (type === "lost") {
            lostItems.value = lostItems.value.filter(
              (item) => item.id !== itemToDelete.value.id
            );
            lostTotal.value -= 1;
          } else {
            foundItems.value = foundItems.value.filter(
              (item) => item.id !== itemToDelete.value.id
            );
            foundTotal.value -= 1;
          }
        } else {
          ElMessage.error(response.data.message || "删除失败");
        }
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败，请稍后再试");
      } finally {
        deleteDialogVisible.value = false;
        itemToDelete.value = null;
      }
    };

    // 分页处理
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      if (activeTab.value === "lost") {
        loadLostItems();
      } else {
        loadFoundItems();
      }
    };

    // 搜索防抖
    let searchTimeout = null;
    const debounceSearch = () => {
      if (searchTimeout) {
        clearTimeout(searchTimeout);
      }

      searchTimeout = setTimeout(() => {
        currentPage.value = 1; // 重置为第一页
        if (activeTab.value === "lost") {
          loadLostItems();
        } else {
          loadFoundItems();
        }
      }, 300);
    };

    // 添加日期格式化函数
    const formatDate = (dateStr) => {
      if (!dateStr) return "";

      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return dateStr; // 如果解析失败，返回原始字符串

      const year = date.getFullYear();
      const month = date.getMonth() + 1; // 月份从0开始
      const day = date.getDate();

      return `${year}/${month}/${day}`;
    };

    onMounted(() => {
      loadLostItems();
    });

    return {
      activeTab,
      loading,
      searchKeyword,
      currentPage,
      pageSize,
      lostTotal,
      foundTotal,
      lostItems,
      foundItems,
      deleteDialogVisible,
      getStatusType,
      viewDetails,
      editItem,
      deleteItem,
      confirmDelete,
      handleCurrentChange,
      loadLostItems,
      loadFoundItems,
      debounceSearch,
      formatDate,
      SearchIcon, // 将图标作为返回值提供给模板
      handleTabChange,
    };
  },
};
</script>

<style scoped>
.user-posts {
  width: 100%;
  max-width: none;
}

.section-title {
  margin-top: 0;
  margin-bottom: 20px;
  color: var(--text-primary);
  font-size: 18px;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 10px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.tab-header .el-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  gap: 10px;
}

.content-scroll-area {
  height: calc(100vh - 300px);
  min-height: 400px;
  flex: 1;
  overflow-y: auto;
}
.xunwu {
  margin-right: 38px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-buttons .el-button {
  padding: 4px;
}

.action-buttons .el-icon {
  font-size: 14px;
}

.el-table {
  min-height: 200px;
}

.tab-content-container {
  overflow: hidden;
}
</style> 